############################################################
## Fraga, Juenke, and Shah 2019: One Run Leads to Another?
## Replication Code: January 2, 2018
## Table A3: Tabular version of results in Main Text
############################################################

# Load Functions #
source('FragaJuenkeShah_Functions.R')

# Load Data #
sl_data <- read.csv("FragaJuenkeShah_JOP_Data.csv", stringsAsFactors=FALSE)

# Remove all districts where 1+ candidates have no race data
sl_data <- subset(sl_data, unknown_cand == 0)

# Change candidate variable to a binary, 0 = no candidate, 1 = one or more candidates
sl_data$white_cand[sl_data$white_cand > 1] <- 1
sl_data$black_cand[sl_data$black_cand > 1] <- 1
sl_data$latino_cand[sl_data$latino_cand > 1] <- 1
sl_data$asian_cand[sl_data$asian_cand > 1] <- 1

# Table A3, Group VAP Needed for 0.5 Probability of Co-Ethnic Candidate Emergence
tabA3 <- rbind(getThresholdsW(0.25, 0.25, sl_data),
	getThresholdsB(0.25, 0.25, sl_data),
	getThresholdsL(0.25, 0.25, sl_data),
	getThresholdsA(0.25, 0.25, sl_data)
	)

getDiff <- function(equ_data){
	equ_data$noInc_Lo <- equ_data$noInc - qnorm(0.975)*equ_data$noInc_SE
	equ_data$noInc_Hi <- equ_data$noInc + qnorm(0.975)*equ_data$noInc_SE
	equ_data$Inc_Lo <- equ_data$Inc - qnorm(0.975)*equ_data$Inc_SE
	equ_data$Inc_Hi <- equ_data$Inc + qnorm(0.975)*equ_data$Inc_SE
	equ_data$Diff <- equ_data[,3] - equ_data[,1]
	equ_data$Diff_SE <- sqrt((equ_data[,4]^2) + (equ_data[,2]^2))
	equ_data$Diff_Lo <- equ_data$Diff - qnorm(0.975)*equ_data$Diff_SE
	equ_data$Diff_Hi <- equ_data$Diff + qnorm(0.975)*equ_data$Diff_SE
	return(equ_data)
}

getDiff(tabA3)